package com.epfresh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.constant.Constant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.ToastUtils;
import com.epfresh.R;
import com.epfresh.utils.TimeStringUtils;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterActivity extends BaseActivity {

    public static final String TAG = "RegisterActivity";
    private EditText phoneEt;
    private EditText codeEt;
    private EditText passwordEt;
    private TextView getcodeTv;
    private Button sureBu;

    private ImageView look_password;
    private FrameLayout look_frame;

    private ImageView read_flag;
    private View readLl;

    private boolean isRequestCode;
    private boolean isDestory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = getApplicationContext();
        read_flag = (ImageView) findViewById(R.id.read_flag);
        read_flag.setOnClickListener(this);
        phoneEt = (EditText) findViewById(R.id.phone_number);
        codeEt = (EditText) findViewById(R.id.code_number);
        passwordEt = (EditText) findViewById(R.id.password_number);
        sureBu = (Button) findViewById(R.id.sure);
        look_frame = (FrameLayout) findViewById(R.id.look_frame);
        look_password = (ImageView) findViewById(R.id.look_password);
        getcodeTv = (TextView) findViewById(R.id.get_code);
        sureBu.setOnClickListener(this);
        look_frame.setOnClickListener(this);
        getcodeTv.setOnClickListener(this);
        readLl = findViewById(R.id.read_ll);
        findViewById(R.id.register_pro).setOnClickListener(this);
        findViewById(R.id.get_read).setOnClickListener(this);
        baseback.setVisibility(View.VISIBLE);
        passwordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();


                if (VerificationUtils.isContainChinese(s)) {
                    toast("密码不能包括中文");
                }

            }
        });
        initData();
    }

    private void initData() {
        basetitle.setText("用户注册");
    }

    boolean passwordflag = false;
    boolean readFlag = true;//是否阅读确认相关协议的标志

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_pro:
                help();
                break;
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.look_frame:
                if (!passwordflag) {
                    look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03_));
                    passwordEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03));
                    passwordEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                passwordflag = !passwordflag;
                passwordEt.postInvalidate();
                CharSequence text = passwordEt.getText();
                if (text != null) {
                    Spannable spanText = (Spannable) text;
                    Selection.setSelection(spanText, text.length());
                }
                break;
            case R.id.get_code:
                // 获取验证码
                if (InputControl.isPhoneNumber(phoneEt) && !isRequestCode) {
                    getcodeTv.setClickable(false);
                    //isAccount();
                    getcodeTv.setText(R.string.getcode_registing);
                    isRequestCode = true;
                    getCodePost();
                } else {
                    getcodeTv.setClickable(true);
                    ToastUtils.TextToast(getApplicationContext(), "请输入合法的手机号码");
                }

                break;
            case R.id.sure:
                if (InputControl.isEmpty(phoneEt)) {
                    T.toast("请输入手机号");
                    return;
                } else {
                    if (!InputControl.isPhoneNumber(phoneEt)) {
                        T.toast("手机号有误，请改正");
                        return;
                    }
                }
                if (InputControl.isEmpty(codeEt) || codeEt.getText().toString().length() != 4) {
                    T.toast("请输入4位验证码");
                    return;
                }
                if (InputControl.isEmpty(passwordEt) || passwordEt.getText().toString().length() < 6) {
                    T.toast("请输入长度至少为6位的密码");
                    return;
                }
                if (VerificationUtils.isContainChinese(passwordEt.getText().toString())) {
                    toast("密码不能包括中文");
                    return;
                }

                if (readFlag == true) {
                } else {
                    ToastUtils.TextToast(this, "请确认相关协议");
                    return;
                }
                register();
                break;
            default:
                break;
        }
    }

    private void help() {

        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_PUR_AGREEMENT);
        intent.putExtra(Constant.KEY_WEB_TITLE, "帮助");
        startActivity(intent);

    }

    /**
     * 注册
     */
    private void register() {

        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_register);
        Map<String, String> map = new HashMap<>();
        map.put("phone", phoneEt.getText().toString());
        map.put("password", passwordEt.getText().toString());
        map.put("verification", codeEt.getText().toString());
        data.setParameters(map);
        request(data, AppPurchaseRouterConstant.cmd_account_acc_register, onRequestListener);
    }

    OnRequestListener<StatusEntity> onRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                Intent main = new Intent(getApplicationContext(), LoginActivity.class);
                main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// 清空已存在的所有Activity
                startActivity(main);
                finish();
                //T.toast(BaseApplication.getDoc().getRegSuccess()); // TODO: 2016/7/1
                return;
            }

        }
    };

    /**
     * 获取验证码
     */
    private void getCodePost() {

        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_getVerification);
        Map<String, String> map = new HashMap<>();
        map.put("phone", phoneEt.getText().toString());
        map.put("type", "1");
        data.setParameters(map);
        request(data, AppPurchaseRouterConstant.cmd_account_acc_getVerification, onRequestCodeListener);
    }
    CountDownTimer timer;

    OnRequestListener<StatusEntity> onRequestCodeListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            isRequestCode = false;

            getcodeTv.setClickable(true);
            getcodeTv.setText(R.string.getcode_regist);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            //token超时
            isRequestCode = false;
            getcodeTv.setClickable(true);
            getcodeTv.setText(R.string.getcode_regist);
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            isRequestCode = false;
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                getcodeTv.setClickable(false);
                //getCodeControl();
                initTime();

            } else {
                getcodeTv.setText(R.string.getcode_regist);
            }

            return;
        }
    };

    public void initTime(){
        if (timer != null) {
            timer.cancel();
        }

        timer = new CountDownTimer(60000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                Log.e("CountDownTimer",""+millisUntilFinished);
                int i = (int)(millisUntilFinished/1000);
                if (i >= 1) {
                    getcodeTv.setClickable(false);
                    getcodeTv.setText(i + "秒后重新发送");
                } else {
                    getcodeTv.setClickable(true);
                    getcodeTv.setText(R.string.getcode_regist);
                }

            }

            @Override
            public void onFinish() {
                getcodeTv.setClickable(true);
                getcodeTv.setText(R.string.getcode_regist);
            }
        };
        timer.start();
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int i = msg.arg1;
            if (i >= 1) {
                getcodeTv.setClickable(false);
                getcodeTv.setText(i + "秒后重新发送");
            } else {
                i = 0;
                getcodeTv.setClickable(true);
                getcodeTv.setText(R.string.getcode_regist);
            }
        }
    };

    /**
     * 获取验证码按钮倒计时控制
     */
    private void getCodeControl() {
        new Thread() {
            int i = 60;
            public void run() {
                try {
                    while (i > 0) {
                        if (isDestory) {
                            return;
                        }
                        Thread.sleep(999);
                        i--;
                        Message message = new Message();
                        message.arg1 = i;
                        handler.sendMessage(message);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        isDestory = true;
        RequestManager.getInstance().cancel("register");
        onRequestListener = null;
        RequestManager.getInstance().cancel("getVerification");
        onRequestCodeListener = null;
        super.onDestroy();
    }
}